#!/usr/bin/python2
#dedopalomera@gmail.com
try:
	import json
except Exception, e:
	import simplejson as json
import urllib
import urllib2
debug = True

class scoreBoard:
	#constantes
	WIN, LOST, DRAW = range(3)
	def __init__(self):
		self.gamesLeft = int()
		self.win = int()
		self.lost = int()
		self.total = int()
		self.lastResult = int()
	def parseResponce(self, res):
		if (res['win'] > self.win):
			self.lastResult = self.WIN
		elif (res['lost'] > self.lost):
			self.lastResult = self.LOST
		else:
			self.lastResult = self.DRAW
		for k,v in res.iteritems():
			self.__dict__[k] = v
		self.total = self.win + self.lost

class PPC:

	def __init__(self, name):
		self.name = name
		self.isLogged = False
		self.url = 'http://ppc.binomio.cl/post.php'
		self.serverUrl = str()
		self.serverID = str()
		self.ID = str()
		self.opponentName = str()
		self.gameType = int()
		self.scoreBoard = scoreBoard()
		self.opLastMove = int()

	def sendMessage(self, data):
		values = {'message':json.dumps(data)}
		data = urllib.urlencode(values)
		req = urllib2.Request(self.url, data)
		dR = urllib2.urlopen(req).read()
		if debug:
			print dR
		res = json.loads(dR)
		if res['isOk']:
			return res
		else:
			raise Exception, res['result']

	
	#despues de llamar a esta funcion, de parte de ambos jugadores
	#se puede tirar nuevamente
	def hasChanges(self):
		ps = {'ID': self.ID, 'serverID': self.serverID}
		data = {'action': 'hasChanges', 'data': ps}
		return self.sendMessage(data)['responce']
	def getChanges(self):
		ps = {'ID': self.ID, 'serverID': self.serverID}
		data = {'action': 'getChanges', 'data': ps}
		ret =  self.sendMessage(data)
		self.scoreBoard.parseResponce(ret['scoreBoard'])
		self.opLastMove = ret['opMov']
		
	
	def getScore(self):
		ps = {'ID': self.ID, 'serverID': self.serverID}
		data = {'action': 'getScore', 'data': ps}
		self.scoreBoard.parseResponce(self.sendMessage(data))
		return self.scoreBoard

	def login(self):
		data = {'action': 'login', 'data': {'userName': self.name}}
		res = self.sendMessage(data)
		self.ID = res['id']
		self.isLogged = True
	def canThrow(self):
		data = {'action': 'canThrow', 'data': {'serverID': self.serverID, 'ID': self.ID}}
		return self.sendMessage(data)['responce']
	# no podra lanzar hasta que los 2 
	#hayan visto el resultado del juego anterior
	def throw(self, movement):
		ps = {'move': movement, 'serverID': self.serverID, 'ID': self.ID}
		data = {'action': 'throw', 'data': ps}
		self.sendMessage(data)
	
			

class PPCClient(PPC):
	#retorna n listas con tuplas de (nombre, tipo, ID),
	#desde la posicion d
	def getServerList(self, d =0, n = 30):
		ps = {'min': d, 'max': n + d}
		return self.sendMessage({'action': 'getServerList', 'data': ps})['responce']
	def joinServer(self, serverID, psw = "none"):
		ps = {'ID': self.ID, 'serverID': serverID, 'psw': psw}
		data = {'action':'join', 'data': ps }
		res = self.sendMessage(data)
		self.serverID = serverID
		self.serverUrl = res['url']
		self.scoreBoard.gamesLeft = res['gamesLeft']
		self.gameType = res['type']
		self.opponentName = res['name']
		
		

class PPCServer(PPC):
	def createServer(self, gType = 1, psw = "none", nRounds = 3):
		pd = {'userName': self.name, 'ID': self.ID, 'psw': psw, 'type': gType, 'nRounds': nRounds}
		data = {'action': 'create', 'data': pd}
		res = self.sendMessage(data)
		self.serverID = res['id']
		self.serverUrl = res['url']
		self.gameType = gType
		self.scoreBoard.gamesLeft = nRounds
		self.psw = psw
	def hasOpponent(self):
		ps = {'serverID': self.serverID, 'userID': self.ID}
		data = {'action': 'checkOpponent', 'data': ps}
		res = self.sendMessage(data)
		if res['isFull']:
			self.opponentName = res['name']
			return True
		return False

if (__name__ == '__main__'):
	name = raw_input("pick a nickname: ");
	resp = raw_input("create server or join [0, 1]: ")
	con = [PPCServer, PPCClient][int(resp)](name)
	print("loggin")
	con.login()
	while(True):
		resp = raw_input("function to call: ")
		if (resp == 'exit'):
			break
		else:
			try:
				print eval("con." + resp)
			except Exception, e:
				print e;
